﻿package idv.cjcat.emitter.behaviors {
	use namespace engine;
	
	import flash.geom.*;
	
	import idv.cjcat.emitter.*;
	
	/**
	 * Behavior trigger triggered by particle position. The test region is rectangle-shaped.
	 */
	public class RectTrigger extends BehaviorTrigger {
		
		/**
		 * Whether the behavior trigger is triggered when a particle enters or leaves the circle-shaped region.
		 */
		public var triggerOnEnter:Boolean;
		
		public var x:Number;
		public var y:Number;
		public var width:Number;
		public var height:Number;
		
		public function RectTrigger(x:Number = 0, y:Number = 0, width:Number = 100, height:Number = 100) {
			this.x = x;
			this.y = y;
			this.width = width;
			this.height = height;
			this.triggerOnEnter = triggerOnEnter;
		}
		
		override public function test(pd:ParticleData):Boolean {
			if (triggerOnEnter) {
				if (contains(pd.cx, pd.cy)) return true;
			} else {
				if (!contains(pd.cx, pd.cy)) return true;
			}
			return false;
		}
		
		private function contains(x:Number, y:Number):Boolean {
			if ((x >= this.x) && (x <= this.x + this.width) && (y >= this.y) && (y <= this.y + this.height )) return true;
			else return false;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = BehaviorTriggerType.RECT;
			xml.@x = x.toString();
			xml.@y = y.toString();
			xml.@width = width.toString();
			xml.@height = height.toString();
			xml.@triggerOnEnter = triggerOnEnter.toString();
			
			return xml;
		}
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			
			this.x = parseFloat(xml.@x);
			this.y = parseFloat(xml.@y);
			this.width = parseFloat(xml.@width);
			this.height = parseFloat(xml.@height);
			triggerOnEnter = (xml.@triggerOnEnter == "true");
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}